package org.dromara.common.job.config;

import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.spi.ILoggingEvent;
import com.aizuda.snailjob.client.common.appender.SnailLogbackAppender;
import com.aizuda.snailjob.client.common.event.SnailClientStartingEvent;
import com.aizuda.snailjob.client.starter.EnableSnailJob;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.EnableScheduling;


/**
 * @Author 刘武贵
 * @Date 2024/8/15 22:00
 * @Description 功能描述：启动定时任务
 */
/**
 * 配置类，用于配置和启用SnailJob任务调度功能
 * 该类通过@AutoConfiguration自动配置，基于条件注解@ConditionalOnProperty来判断是否启用SnailJob功能
 * 使用@EnableScheduling和@EnableSnailJob注解来启用定时任务和SnailJob的具体功能
 */
@AutoConfiguration
@ConditionalOnProperty(prefix = "snail-job", name = "enabled", havingValue = "true")
@EnableScheduling
@EnableSnailJob
public class SnailJobConfig {

    /**
     * 监听SnailClient启动事件，以配置日志收集器
     * 该方法通过创建并添加一个自定义的SnailLogbackAppender到根日志记录器，来实现日志的特定处理
     * 这样可以确保在SnailClient启动时，日志能够正确地通过我们定义的途径进行收集和处理
     *
     * @param event SnailClientStartingEvent事件对象，提供了SnailClient启动时的相关信息
     */
    @EventListener(SnailClientStartingEvent.class)
    public void onStarting(SnailClientStartingEvent event) {
        // 获取LoggerFactory的上下文
        LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
        // 创建并配置SnailLogbackAppender
        SnailLogbackAppender<ILoggingEvent> ca = new SnailLogbackAppender<>();
        ca.setName("snail_log_appender");
        ca.start();
        // 获取根日志记录器并添加自定义的appender
        Logger rootLogger = lc.getLogger(Logger.ROOT_LOGGER_NAME);
        rootLogger.addAppender(ca);
    }

}
